package com.gin.kotlin.gf2gamecommunity.routes

import android.util.Log
import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Create
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import androidx.navigation.toRoute
import androidx.paging.compose.collectAsLazyPagingItems
import com.gin.kotlin.enums.QueryType
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.composable.MessageIconButton
import com.gin.kotlin.gf2gamecommunity.composable.OpenLinkButton
import com.gin.kotlin.gf2gamecommunity.composable.TopicLazyColumn
import com.gin.kotlin.gf2gamecommunity.navi.GF2Navigator
import com.gin.kotlin.gf2gamecommunity.viewmodel.CommunityIndexViewModel
import com.gin.kotlin.gf2gamecommunity.viewmodel.MessageViewModel
import com.gin.kotlin.gf2gamecommunity.viewmodel.TopicListViewModel
import kotlinx.coroutines.launch
import kotlinx.serialization.Serializable


/**
 * 扩展方法
 * @receiver [NavGraphBuilder]
 */
fun NavGraphBuilder.topicList(navigator: GF2Navigator, messageViewModel: MessageViewModel) = composable<TopicListRoute>(
    // 从屏幕右侧进入，持续500毫秒
    enterTransition = { slideInHorizontally(tween(500)) { it } },
    // 从屏幕右侧退出，持续500毫秒
    exitTransition = { slideOutHorizontally(tween(500)) { it } }) {
    TopicListComposable(navigator = navigator, route = it.toRoute(), messageViewModel = messageViewModel)
}

/**
 * 主题列表路线
 * @param queryType 查询类型
 * @param userId 用户ID ， 查询用户发帖时使用
 * @param themeId 话题ID
 * @param categoryId 类型ID
 * @param sortType 排序
 * @param hotValue 翻页参数：
 * @param lastTid 翻页参数：
 * @param pubTime 翻页参数：
 * @param replyTime 翻页参数：
 * @constructor
 */
@Serializable
data class TopicListRoute(
    val queryType: QueryType,
    val userId: Int? = null,
    val themeId: Int? = null,
    val categoryId: Int? = null,
    val sortType: Int = 1,
    val hotValue: Int = 0,
    val lastTid: Int = 0,
    val pubTime: Int = 0,
    val replyTime: Int = 0,
)

/**
 * 主题路线组件
 * @param route 路线
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TopicListComposable(
    navigator: GF2Navigator,
    route: TopicListRoute,
    viewModel: TopicListViewModel = viewModel(),
    communityIndexViewModel: CommunityIndexViewModel = viewModel(),
    messageViewModel: MessageViewModel = viewModel()
) {
    @Suppress("LocalVariableName") val TAG = "TopicListComposable"

    navigator.apply {
        val coroutineScope = rememberCoroutineScope()
        //  加载主题分类
        val categoryState = communityIndexViewModel.categories.liveData.observeAsState()
        communityIndexViewModel.categories.fetch()
        // paging加载主题列表
        val lazyPagingItems = viewModel.topicList.fetch(route).collectAsLazyPagingItems()
        val lazyListState = rememberLazyListState()


        val toppedTopics = route.categoryId?.let { viewModel.toppedTopic.fetch(it).observeAsState() }?.value?.data

        fun refresh() {
            Log.i(TAG, "刷新")
            lazyPagingItems.refresh()
            coroutineScope.launch { lazyListState.scrollToItem(0, 0) }
        }

        // 发帖后刷新
        if (lazyPagingItems.itemCount > 0 && App.INSTANCE.replyFlag) {
            refresh()
        }

        Scaffold(
            topBar = {
                TopAppBar(navigationIcon = {
                    IconButton(onClick = { onPopBackStack() }) {
                        Icon(imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "后退")
                    }
                }, actions = {
                    OpenLinkButton(navigator)
                    IconButton(onClick = { onNavigateToSearch(SearchRoute()) }) {
                        Icon(imageVector = Icons.Filled.Search, contentDescription = "搜索")
                    }

                    MessageIconButton({ onNavigateToMessageList(it) }, messageViewModel)

                    IconButton(onClick = { refresh() }) {
                        Icon(imageVector = Icons.Filled.Refresh, contentDescription = "刷新")
                    }
                }, title = {
                    Text(categoryState.value?.firstOrNull { it.id == route.categoryId }?.name ?: "<主题分类>")
                }
                )
            },
            floatingActionButton = {
                Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.background(
                    MaterialTheme.colorScheme.background.copy(alpha = 0.8f), RoundedCornerShape(16.dp))) {
                    route.categoryId?.let {
                        IconButton(onClick = { onNavigateToPublish(PublishRoute(it)) }) {
                            Icon(imageVector = Icons.Filled.Create, contentDescription = "发布主题")
                        }
                    }
                }
            }
        ) { innerPadding ->
            val modifier = Modifier.padding(innerPadding)
            Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = modifier
                .fillMaxSize()
                .padding(8.dp)) {
                if (lazyPagingItems.itemCount == 0) {
                    Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                        CircularProgressIndicator()
                    }
                } else {
                    TopicLazyColumn(lazyPagingItems = lazyPagingItems,
                        toppedTopics = toppedTopics,
                        onNavigateToCommentList = { r -> onNavigateToCommentList(r) },
                        state = lazyListState)
                }
            }
        }
    }
}
